#include <set>
#include <fstream>

#include "CLSystemWriter.h"
#include "CLSystem.h"
#include "CSysErrorMsg.h"
#include "CLSysErrorMsg.h"

CLSystemWriter::CLSystemWriter(CLSystem const* ptr_ls)
    : ptr_lsystem(ptr_ls)
{
}

void CLSystemWriter::Write(std::string const& fn) const
{
    ptr_lsystem->TestLSystem();

    std::ofstream file_out(fn.c_str(),std::ios_base::trunc);
    if(!file_out)
        throw CSysErrorMsg(CSysErrorMsg::SYS_FILE_ERR,fn);

    std::string str;
    ptr_lsystem->GetName(str);

    file_out << str << '(' 
             << ptr_lsystem->GetLength() << ',' 
             << ptr_lsystem->GetLengthFactor() << ','
             << ptr_lsystem->GetAngle() << ',' 
             << ptr_lsystem->GetDAngle() << ','
             << ptr_lsystem->GetIterationDepth()
             << ")\n";

    file_out << "{\n";
  
    std::set<char> antecedents;
    ptr_lsystem->GetProductionAntecedents(antecedents);

    std::string axiom;
    ptr_lsystem->GetAxiom(axiom);
    file_out << "\"" << axiom << "\"\n";

    std::set<char>::const_iterator it_set(antecedents.begin());
    while(it_set != antecedents.end())
    {
        char c(*it_set);
        ptr_lsystem->GetFormattedConsequent(c,str);

        file_out << c << " -> \"" << str << "\"\n";

        it_set++;
    }
  
    file_out << '}' << std::endl;
}
